﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;
using System.Web.Script.Services;

namespace Nivdal
{
    public partial class Preferences : System.Web.UI.Page
    {
        private string TeamuploadDirectory;
        private string UseruploadDirectory;
        private string UseruploadDirectorySmall;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Preferences_PageTitle;
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");

            //TextBox EmailTextBox = FormView1.FindControl("EmailTextBox") as TextBox;

            //if (EmailTextBox == null)
            //{
            //    //throw exception?
            //    this.MessageLabel.Text = "could not locate text box";
                
            //}
            //EmailTextBox.Attributes["onblur"] = "checkEmailUsage(this.value);";

            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            //this.Title = GND.ReturnAppTitle();

            this.SqlDataSource1.UpdateParameters.Add("UserId", ou.UserId);
            //Response.Write(UsrId);
            if (!Page.IsPostBack)
            {
                this.SqlDataSource1.SelectParameters.Add("UserId", ou.UserId);
                this.ShowStadiumsValuesSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
                //this.SqlDataSource1.UpdateParameters.Add("UserId", UsrId);
                //this.SqlDataSource2.SelectParameters.Add("UserId", UsrId);
            }


            // team name change button
            ChangeTeamNameHyperlink.Visible = GND.ReadNivdalBoolData("Nivdal_CanChangeTeamName");

            //place files in website subfolder named TeamLogos
            TeamuploadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "TeamLogos");
            UseruploadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "UserPictures");
            UseruploadDirectorySmall = Path.Combine(
               Request.PhysicalApplicationPath, "UserSmallPictures");
            this.UploadUserPictureButton.OnClientClick = "return confirm('" + Resources.Resource.UploadLogoConformationText + "')";
            this.UploadTeamLogoButton.OnClientClick = "return confirm('" + Resources.Resource.UploadLogoConformationText + "')";
            if (!IsPostBack)
            {
                TextBox EmailTextBox = FormView1.FindControl("EmailTextBox") as TextBox;

                this.Currentemail.Value = EmailTextBox.Text;
                EmailTextBox.Attributes["onblur"] = "checkEmailUsage(this.value);";
            }
        }

        protected void SubmitChanges(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string PublicName = (FormView1.FindControl("PublicNameTextBox") as TextBox).Text.Trim();
            string LoginName = (FormView1.FindControl("LoginNameTextBox") as TextBox).Text.Trim();
            string RealFirstName = (FormView1.FindControl("RealFirstNameTextBox") as TextBox).Text.Trim();
            string RealLastName = (FormView1.FindControl("RealLastNameTextBox") as TextBox).Text.Trim();
            string PreferredLanguage = (FormView1.FindControl("PreferredLanguageDropDownList") as DropDownList).SelectedValue;
            string ForumSignature = (FormView1.FindControl("ForumSignatureTextBox") as TextBox).Text.Trim();
            bool ForumShowSignature = (FormView1.FindControl("ForumShowSignatureCheckBox") as CheckBox).Checked;
            bool ForumUseSignature = (FormView1.FindControl("ForumUseSignatureCheckBox") as CheckBox).Checked;
            //bool AnonymousVisits = (FormView1.FindControl("AnonymousVisitsCheckBox") as CheckBox).Checked;
            bool ChatAvailable = (FormView1.FindControl("AvailableVorChatCheckBox") as CheckBox).Checked;
            string Email = (FormView1.FindControl("EmailTextBox") as TextBox).Text.Trim();
            //bool UseAdvancedMatchInstructions = (FormView1.FindControl("AdvancedMatchInstructions") as CheckBox).Checked;
            string FanClubName = (FormView1.FindControl("FansClubNameTextBox") as TextBox).Text.Trim();
            string DefaultStadiumId = (FormView1.FindControl("StadiumsDropDownList") as DropDownList).SelectedValue;
            string DefaultFreindlyStadiumId = (FormView1.FindControl("FriendlyStadiumsDropDownList") as DropDownList).SelectedValue;
            bool UseEmail = (FormView1.FindControl("EmailCheckbox") as CheckBox).Checked;
            bool AllowPasswordReset = (FormView1.FindControl("AllowPasswordResetCheckbox") as CheckBox).Checked;


            SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand storedProcCommand = new SqlCommand("Nivdal_UpdateUserPreferences", myConnection);
            storedProcCommand.CommandType = CommandType.StoredProcedure;

            storedProcCommand.Parameters.Add("UserId", SqlDbType.NVarChar);
            storedProcCommand.Parameters.Add("PublicName", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("LoginName", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("RealFirstName", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("RealLastName", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("PreferredLanguage", SqlDbType.Decimal, 3);
            storedProcCommand.Parameters.Add("ForumSignature", SqlDbType.NVarChar, 128);
            storedProcCommand.Parameters.Add("ForumShowSignature", SqlDbType.Bit);
            storedProcCommand.Parameters.Add("ForumUseSignature", SqlDbType.Bit);
            //storedProcCommand.Parameters.Add("AnonymousVisits", SqlDbType.Bit);
            storedProcCommand.Parameters.Add("AvailableForChat", SqlDbType.Bit);
            storedProcCommand.Parameters.Add("Email", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("UseAdvancedMatchInstructions", SqlDbType.Bit);
            storedProcCommand.Parameters.Add("FanClubName", SqlDbType.NVarChar, 256);
            storedProcCommand.Parameters.Add("DefaultStadiumId", SqlDbType.Decimal, 12);
            storedProcCommand.Parameters.Add("DefaultFreindlyStadiumId", SqlDbType.Decimal, 12);
            storedProcCommand.Parameters.Add("UseEmail", SqlDbType.Bit);
            storedProcCommand.Parameters.Add("AllowPasswordReset", SqlDbType.Bit);

            storedProcCommand.Parameters["UserId"].Value = ou.UserId;
            storedProcCommand.Parameters["PublicName"].Value = PublicName;
            storedProcCommand.Parameters["LoginName"].Value = LoginName;
            storedProcCommand.Parameters["RealFirstName"].Value = RealFirstName;
            storedProcCommand.Parameters["RealLastName"].Value = RealLastName;
            storedProcCommand.Parameters["PreferredLanguage"].Value = PreferredLanguage;
            storedProcCommand.Parameters["ForumSignature"].Value = ForumSignature;
            storedProcCommand.Parameters["ForumShowSignature"].Value = ForumShowSignature;
            storedProcCommand.Parameters["ForumUseSignature"].Value = ForumUseSignature;
            //storedProcCommand.Parameters["AnonymousVisits"].Value = AnonymousVisits;
            storedProcCommand.Parameters["AvailableForChat"].Value = ChatAvailable;
            storedProcCommand.Parameters["Email"].Value = Email;
            //storedProcCommand.Parameters["UseAdvancedMatchInstructions"].Value = UseAdvancedMatchInstructions;
            storedProcCommand.Parameters["FanClubName"].Value = FanClubName;
            storedProcCommand.Parameters["DefaultStadiumId"].Value = DefaultStadiumId;
            storedProcCommand.Parameters["DefaultFreindlyStadiumId"].Value = DefaultFreindlyStadiumId;
            storedProcCommand.Parameters["UseEmail"].Value = UseEmail;
            storedProcCommand.Parameters["AllowPasswordReset"].Value = AllowPasswordReset;

            try
            {
                myConnection.Open();
                storedProcCommand.ExecuteNonQuery();
                GND.SendPendingMails();
            }
            //catch
            //{
            //    //Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "<script type=\"text/javascript\">alert('" + SQLDBException.Message + "');</script>");
            //    return false;
            //}

            finally
            {
                // Close the connection when done with it.
                myConnection.Close();

            }

            //((OnlineUser)Session["User"]).Language = PreferredLanguage;
            //((OnlineUser)Session["User"]).Culture = GND.ReadNivdalStringData("@UserId", "Nivdal_GetUserCulture", ou.UserId);
            //((OnlineUser)Session["User"]).UICulture = GND.ReadNivdalStringData("@UserId", "Nivdal_GetUserUICulture", ou.UserId);
            //((OnlineUser)Session["User"]).TextDir = GND.ReadNivdalStringData("UserId", "Nivdal_GetUserTextDirection", ou.UserId);
            
            ou.RefreshOU();
            
            Response.Redirect("Preferences.aspx");
        }

        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }

        public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }



        public System.Drawing.Bitmap ResizeImgFile(System.Drawing.Bitmap img, int width, int height)
        {

            System.Drawing.Bitmap ResizedImg = ResizeImage(img, width, height, ResizeOptions.MaxWidthAndHeight);
            return ResizedImg;

        }


        public bool CheckImgFile(string FileExtantion)
        {

            if (FileExtantion.Equals(".jpg") || (FileExtantion.Equals(".gif")) || (FileExtantion.Equals(".bmp")) || (FileExtantion.Equals(".png")))
                return true;
            else
                return false;
        }


        protected void UploadTeamLogoButton_Click(object sender, EventArgs e)
        {
           
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            //Get the current picture url for delete after uploading the new one
            string CurrentImageURL; //will be the old one after uploading a new picture
            CurrentImageURL = GND.ReadNivdalStringData("TeamId", "Nivdal_GetTeamLogo", ou.TeamId);
            string ImageName = CurrentImageURL.Substring(CurrentImageURL.LastIndexOf('/') + 1);
            //this.MessageLabel.Text = "ImageName is: " + CurrentImageURL + " Full URL is: " + (MapPath(".") + ("\\TeamLogos\\" + ImageName));



            Random rnd = new Random();
            //string num = rnd.Next(1000).ToString();
            string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
                DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            // = random.Next(1000);
            int intFileSizeLimit = 2000;
            bool IsImageInput = false;
            //bool IsImageGood = false;
            //bool IsDetailsGood = false;
            this.ErrorLabel.Text = "";
            string extension = Path.GetExtension(TeamLogoFileUpload.PostedFile.FileName);
            string filenameNoExtension = Path.GetFileNameWithoutExtension(TeamLogoFileUpload.PostedFile.FileName);
            //string ServerfileName = filenameNoExtension + num + extension; 
            string ServerfileName = num + extension;
            //string ServerfileName = Path.GetFileName(TeamLogoFileUpload.PostedFile.FileName);
            string FullUploadPath = Path.Combine(TeamuploadDirectory, ServerfileName);
            string FileExtantion = (Path.GetExtension(TeamLogoFileUpload.FileName).ToLower());
            string ImagePath = "~/TeamLogos/" + ServerfileName;
            if (!(TeamLogoFileUpload.HasFile && TeamLogoFileUpload.PostedFile != null))//first check if the user uploaded file
                IsImageInput = false;//There is no image file

            else //There is image input
                IsImageInput = true;


            //check if the image file has the right extantion and size
            if (IsImageInput && CheckImgFile(FileExtantion) && TeamLogoFileUpload.PostedFile.ContentLength / 1024 < intFileSizeLimit)
            {
                System.Drawing.Bitmap ResizedTeamLogo = ResizeImgFile(new System.Drawing.Bitmap(TeamLogoFileUpload.PostedFile.InputStream), 150, 150);
                //System.Drawing.Bitmap ResizedTeamLogo = new System.Drawing.Bitmap(TeamLogoFileUpload.PostedFile.InputStream);

                try
                {
                    //ResizedTeamLogo.SetResolution(150,150);
                    ResizedTeamLogo.Save(FullUploadPath);
                    

                    //TeamLogoFileUpload.PostedFile.SaveAs(FullUploadPath);
                    ///SponsorFileUpload.PostedFile.SaveAs(FullUploadPath);
                    //ErrorLabel.Text = "File " + ServerfileName;
                    //     ErrorLabel.Text += " uploaded successfully to";
                    //ErrorLabel.Text += FullUploadPath;
                    //ErrorLabel.Text = FullUploadPath;
                }
                catch (Exception err)
                {
                    this.ErrorLabel.Text = err.Message + FullUploadPath + ServerfileName;
                    IsImageInput = false;
                }
            }

            else
            {
                ErrorLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError + " ";


            }

            if (IsImageInput)
            {
                string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
                System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
                dbCommand.CommandText = "Nivdal_SetTeamLogo";
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.Connection = dbConnection;

                SqlParameter dbParam_UserId = new SqlParameter();
                dbParam_UserId.ParameterName = "@UserId";
                dbParam_UserId.Value = ou.UserId;
                dbParam_UserId.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_UserId);

                SqlParameter dbParam_Logo = new SqlParameter();
                dbParam_Logo.ParameterName = "@Logo";
                dbParam_Logo.Value = ImagePath;
                dbParam_Logo.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_Logo);

                try
                {

                    dbConnection.Open();
                    dbCommand.ExecuteScalar();

                    if (!ImageName.Contains("menupicture.gif"))
                        File.Delete((MapPath(".") + ("\\TeamLogos\\" + ImageName)));
                }
                catch
                { }

                finally
                {
                    dbConnection.Close();
                }

            }
        }

        protected void UploadUserPictureButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            //Get the current picture url for delete after uploading the new one
            string CurrentPictureURL; //will be the old one after uploading a new picture
            ///string TempCurrentPictureURL;
            CurrentPictureURL = GND.ReadNivdalStringData("UserId", "Nivdal_GetUserPicture", ou.UserId);
            string PicName = CurrentPictureURL.Substring(CurrentPictureURL.LastIndexOf('/') + 1);

            Random rnd = new Random();
            //string num = rnd.Next(1000).ToString();
            string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
                        DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                        DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            int intFileSizeLimit = 2000;
            bool IsImageInput = false;
            this.ErrorLabel.Text = "";
            string extension = Path.GetExtension(UserPictureFileUpload.PostedFile.FileName);
            string filenameNoExtension = Path.GetFileNameWithoutExtension(UserPictureFileUpload.PostedFile.FileName);
            //string ServerfileName = filenameNoExtension + num + extension; 
            string ServerfileName = num + extension;
            string FullUploadPath = Path.Combine(UseruploadDirectory, ServerfileName);
            string FullUploadPathSmall = Path.Combine(UseruploadDirectorySmall, ServerfileName);
            string FileExtantion = (Path.GetExtension(UserPictureFileUpload.FileName).ToLower());
            string ImagePath = "~/UserPictures/" + ServerfileName;
            string SmallImagePath = "~/UserSmallPictures/" + ServerfileName;
            if (!(UserPictureFileUpload.HasFile && TeamLogoFileUpload.PostedFile != null))//first check if the user uploaded file
                IsImageInput = false;//There is no image file

            else //There is image input
                IsImageInput = true;


            //check if the image file has the right extantion and size
            if (IsImageInput && CheckImgFile(FileExtantion) && UserPictureFileUpload.PostedFile.ContentLength / 1024 < intFileSizeLimit)
            {
                System.Drawing.Bitmap ResizedUserPicture = ResizeImgFile(new System.Drawing.Bitmap(UserPictureFileUpload.PostedFile.InputStream), 150, 150);
                System.Drawing.Bitmap MoreResizedUserPicture = ResizeImgFile(new System.Drawing.Bitmap(UserPictureFileUpload.PostedFile.InputStream), 56, 56);
                try
                {
                    ResizedUserPicture.Save(FullUploadPath);
                    MoreResizedUserPicture.Save(FullUploadPathSmall);
                    //MessageLabel.Text = "path is: " + (MapPath(".") + ("\\UserPictures\\" + PicName));
                    File.Delete((MapPath(".") + ("\\UserPictures\\" + PicName)));
                    File.Delete((MapPath(".") + ("\\UserSmallPictures\\" + PicName)));
                   
                }
                catch (Exception err)
                {
                    this.ErrorLabel.Text = err.Message;
                    IsImageInput = false;
                }
            }

            else
            {
                ErrorLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError;

            }

            if (IsImageInput)
            {

                
                string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
                System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
                dbCommand.CommandText = "Nivdal_SetUserPicture";
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.Connection = dbConnection;

                SqlParameter dbParam_UserId = new SqlParameter();
                dbParam_UserId.ParameterName = "@UserId";
                dbParam_UserId.Value = ou.UserId;
                dbParam_UserId.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_UserId);

                SqlParameter dbParam_Picture = new SqlParameter();
                dbParam_Picture.ParameterName = "@Picture";
                dbParam_Picture.Value = ImagePath;
                dbParam_Picture.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_Picture);

                try
                {

                    dbConnection.Open();
                    dbCommand.ExecuteScalar();
                   
                }
                catch (Exception SQLDBException)
                {
                    this.ErrorLabel.Text = Convert.ToString(SQLDBException);
                    return;

                }

                finally
                {
                    dbConnection.Close();
                }

            }

        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }
        /// <summary>
        /// Static method that retrieves the time from the server
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.WebMethod]
        public static bool IsEmailAvailable(string Email)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            try
            {
                return (GND.ReadNivdalBoolData("@Email", "NewSponsorIsEmailAvailable", Email));
            }
            catch
            {
                return false;
            }

        }


        public void test()
        {
            Response.Write("Hi");
        }

        [System.Web.Services.WebMethod]
        public static string WS_ReturnTranslatedString(string StringToTranslate)
        {
            string RerurnValue = "";
            switch (StringToTranslate)
            {
                case "EmailIsTaken":
                    RerurnValue = (Resources.SponsorsResource.NewSponsor_EmailIsTaken);
                    break;
                case "BannerFileRequire":
                    RerurnValue = (Resources.SponsorsResource.NewSponsor_BannerFileIsRequire);
                    break;
            }

            return RerurnValue;

        }

    }

}